#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8024
int main()
{
        /* 创建socket */
        int sockfd = socket(AF_INET,SOCK_STREAM,0);
        if(sockfd == -1)
        {
                perror("socket failed!");
                exit(-1);
        }
        /* 准备地址 */
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(PORT);
        inet_aton("127.0.0.1", &addr.sin_addr);
        /* 绑定 */
        int res = bind(sockfd, (struct sockaddr *)&addr,sizeof(addr));
        if(res == -1)
        {
                perror("bind failed ");
                exit(-1);
        }
        /* 监听接口 */
        if(listen(sockfd, 100) == -1)
        {
                perror("listen failed ");
                exit(-1);
        }
        /* 等待客户端连接 */
        struct sockaddr_in fromaddr; //客户端地址
        socklen_t len = sizeof(fromaddr);//注意len初始值一定不为0
        int new_sd = accept(sockfd, (struct sockaddr *)&fromaddr, &len);
        if(new_sd == -1)
        {
                perror("accept failed!");
                exit(-1);
        }
        char *from_ip = inet_ntoa(fromaddr.sin_addr);
        printf("有一个客户端连接到服务器，他的IP: %s\n",from_ip);
        /* 处理客户端数据 */
        char buf[100] = {0};
        int ret = read(new_sd, buf, sizeof(buf));
        if(ret < 0)
        {
                perror("read failed");
                exit(-1);
        }
        else
        {
                printf("从客户端读到数据，内容是%s\n", buf);
        }
        char *str = "欢迎光临";
        write(new_sd, str, strlen(str));
        /* 关闭连接 */
        close(new_sd);
        close(sockfd);
        return 0;
}
